<script setup lang="ts">
import {nextTick, onMounted, onUnmounted, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import {Quote, QuoteListParam} from "@/api/quote/type";
import {addApi, deleteApi, editApi, getListApi} from "@/api/quote";
import {Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'
// 引入统一格式化工具
import { formatPrice } from '@/utils/formatter'
import QuoteForm from './components/QuoteForm.vue'

// 表格高度自适应
const tableHeight = ref(0)

// 表格相关
const tableData = ref([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 查询表单
const searchForm = reactive<QuoteListParam>({
  quoteNumber: undefined,
  title: undefined,
  page: 1,
  limit: 10
})

// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  searchForm.quoteNumber = undefined
  searchForm.title = undefined
  search()
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    let res = await getListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除报价单
const deleteOne = async (id: number) => {
  try {
    await deleteApi(id)
    ElMessage.success('删除成功')
    if (tableData.value.length === 1 && paginationData.currentPage > 1) {
      paginationData.currentPage--
    }
    getTableData()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 表单显示控制
const showForm = ref(false)
const formMode = ref<string>('add')
const currentQuoteId = ref<number>()

// 新增报价单
const handleAdd = () => {
  formMode.value = 'add'
  currentQuoteId.value = undefined
  showForm.value = true
}

// 编辑报价单
const handleEdit = (row: Quote) => {
  formMode.value = 'edit'
  currentQuoteId.value = row.id
  showForm.value = true
}

// 查看报价单详情
const handleView = (row: Quote) => {
  formMode.value = 'view'
  currentQuoteId.value = row.id
  showForm.value = true
}

// 保存成功后的回调
const handleSaveSuccess = () => {
  showForm.value = false
  getTableData()
}

// 取消操作
const handleCancel = () => {
  showForm.value = false
}

// 生命周期钩子
onMounted(() => {
  getTableData()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 268
  })
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 268
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <!-- 左侧列表 -->
  <el-main v-if="!showForm">
    <el-card class="search-card">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="报价单号">
          <el-input v-model="searchForm.quoteNumber" placeholder="请输入报价单号"/>
        </el-form-item>
        <el-form-item label="报价标题">
          <el-input v-model="searchForm.title" placeholder="请输入报价标题"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <el-icon>
              <Search/>
            </el-icon>
            查询
          </el-button>
          <el-button @click="reset">
            <el-icon>
              <Refresh/>
            </el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon>
              <Plus/>
            </el-icon>
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-table
        v-loading="loading"
        :data="tableData"
        border
        :height="tableHeight"
        style="width: 100%;margin-top: 15px"
    >
      <el-table-column type="index" label="序号" width="70"/>
      <el-table-column prop="quoteNumber" label="报价单号" min-width="120"/>
      <el-table-column prop="title" label="报价标题" min-width="150"/>
      <el-table-column prop="validUntil" label="有效期至" min-width="120"/>
      <el-table-column prop="totalAmount" label="总金额" min-width="120">
        <template #default="scope">
          {{ formatPrice(scope.row.totalAmount) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'DRAFT' ? 'info' : scope.row.status === 'SUBMITTED' ? 'warning' : 'success'">
            {{ scope.row.status === 'DRAFT' ? '草稿' : scope.row.status === 'SUBMITTED' ? '已提交' : '已确认' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" min-width="200" show-overflow-tooltip/>
      <el-table-column label="操作" width="190" fixed="right">
        <template #default="scope">
          <el-button type="success" size="small" link @click="handleEdit(scope.row)">
            <el-icon>
              <Edit/>
            </el-icon>
            编辑
          </el-button>
          <el-button type="primary" size="small" link @click="handleView(scope.row)" icon="view">查看</el-button>
          <el-button type="danger" size="small" link @click="deleteOne(scope.row.id)">
            <el-icon>
              <Delete/>
            </el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="paginationData.currentPage"
        v-model:page-size="paginationData.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="paginationData.total"
        layout="total, sizes, prev, pager, next"
        class="pagination"
        @size-change="getTableData"
        @current-change="getTableData"
    />
  </el-main>

  <!-- 右侧表单 -->
  <el-main v-else>
    <QuoteForm
        :quote-id="currentQuoteId"
        :mode="formMode"
        @save-success="handleSaveSuccess"
        @cancel="handleCancel"
    />
  </el-main>
</template>

<style scoped lang="scss">
.el-pagination {
  margin-top: 10px;
  justify-content: flex-end;
}

.search-card {
  height: 70px;
}
</style>
